# MyWiki is a program based on Ruby on Rails developed as part of a class
# project for the Fall 2008 session on CmpE 275 at SJSU. This program 
# sets up a Wiki system supporting creating, editing, and deleting rich text
# pages. It supports built in full text search on page titles, tags, description
# and body, using Ferret RoR module. This program also supports a rich
# text based editor using TinyMCE plugin with added functionality of
# identifying and converting WikiWords to URL and supporting raw
# wiki text editing using RedCloth gem.
#
# Author::	Sonali Goel (mailto: sonaligoel83@gmail.com)
# Copyright:: Copyright (c) SJSU 2008
# This class defines the user action supported by the program
class MywikiController < ApplicationController

  # Display the login page
  def login
	@page = "login"; p 'Page: '+@page
	@search = false
	@puser = false
  end
  
  # Called from the login page to create user session. Expects user as parameter. 
  def dologin
	@page = "dologin"; p 'Page: '+@page
	@usr = params[:user]
	p @usr
	p @usr[:userid]
	#@mywiki_user = MywikiUser.find(@usr[:userid])
	@mywiki_user = MywikiUser.find(:all, :conditions => "id = "+@usr[:userid])
	p @mywiki_user
	if @mywiki_user.length == 0
		flash[:error] = 'Login failed.'
		redirect_to :back
	else
		session[:user_id]=@usr[:userid]
		p 'User id stored'+session[:user_id]

		if @mywiki_user[0]['user'] == "admin"
			redirect_to :controller => 'mywiki_user', :action => :manage
		else			
			redirect_to :action => :index
		end		
	end
  end
  
  # call to logout of system
  def logout
	session[:user_id] = nil
	session = nil
	redirect_to :controller => 'home', :action => :index
  end
  
  # If the user is logged in, display mywiki home page 
  def index
	@page = "index"; p 'Page: '+@page
	get_user
	@mywikis = Mywiki.find(:all, :select => "distinct *", :limit => 10, :order => "updated_at desc" )
  end

  # If the user has create permission, display new page creation form,
  # otherwise redirect to mywiki index.
  def new
	@page = "new"; p 'Page: '+@page
	get_user
	@priv = @user['c_priv']
	p @user
	p @priv
	if @priv == false 
	  flash[:error] = 'You do not have permission to create pages'	  	 
	  redirect_to :action => :index		
	else 
		# do not show search form with create new page form
		@search = false
		gen_content
		
	    @mywiki = Mywiki.new
		if params[:f].nil?
			#noop
		else
			@mywiki.title = params[:f]
		end
		@mywiki.userid = @id		
	end	
  end
  
  # called from new page creation
  def create
	@mywiki = Mywiki.new(params[:mywiki])
	get_user
	@mywiki.userid = @id;
	p @mywiki
	@title = @mywiki.title
	p @title
	if @title.nil? || @title.strip.length == 0
	    p 'in if....'
		flash[:error] = 'Wiki page could not be created with empty title!'		
	else
	    p 'in else...'
		@exist_wiki = Mywiki.find(:all, :conditions => "title = '"+@title+"'" );
		p @exist_wiki
		if @exist_wiki.nil? || @exist_wiki.length == 0
		    p 'saving'
			@mywiki.save		
		else
			p 'Error'
			flash[:error] = 'Wiki page '+@title+' already exists!'		
		end
	end
    redirect_to :action => :view, :f => @title	
  end
  
  # If user has edit permission, show edit existing page form, otherwise
  # redirect user to mywiki index page. Trying to edit non existent page 
  # will be redirected to creating new page with the same title.
  def edit
	@page = "edit"; p 'Page: '+@page
	get_user
	@priv = @user['e_priv']
	if @priv == false 
	  flash[:error] = 'You do not have permission to edit pages'
	  redirect_to :action => :index		
	else 
		# do not display search form with edit page form
		@search = false
		gen_content
		@mywiki = Mywiki.find(:all, :conditions => "title = '"+params[:f]+"'" );
		if @mywiki.nil? || @mywiki.length == 0
			flash[:error] = 'Page ' + params[:f] + ' does not exist. Create new below:'
			redirect_to :action => :new, :f => params[:f]
		end
	end
  end
  
  # Update called when submitting  edit form
  def update
	get_user	
	@mywiki = Mywiki.find(params[:mywiki]['id']);	
	@mywiki.userid = @id;
	if @mywiki.update_attributes(params[:mywiki])
		flash[:notice] = 'Page was successfully updated.'        
	else
		flash[:error] = 'Page could not be updated.'
	end
	redirect_to :action => :view, :f => @mywiki.title 
  end
  
  # If user has read permission, view the specified wiki page, otherwise 
  # redirect to login page. If the page does not exist, user is redirected to
  # creating new page with the specified title.  
  def view
	@page = "view"; p 'Page: '+@page
	@view = true
	gen_content
	get_user
	@priv = @user['r_priv']
	if @priv == false 
	  flash[:error] = 'You do not have permission to view pages'
	  redirect_to :controller => 'home', :action => :index
	else 		
		#@mywiki = Mywiki.find(params[:id])
		@mywikis = Mywiki.find(:all, :conditions => "title = '"+params[:f]+"'" );
		p 'length'
		p @mywikis.length
		if @mywikis.length == 0
			flash[:error] = 'Page does not exist. Create new.'
			redirect_to :action => :new, :f => params[:f]
		else
			@CamelCase = Regexp.new( '\b((?:[A-Z]\w+){2,})' )
			p @mywikis[0]['body']
			p @mywikis[0]['body'].gsub!( @CamelCase, '<a href="/mywiki/\1">\1</a>' )
			p @mywikis[0]['body']
		
			@filestat = @mywikis[0]['created_at']
			@filename = @mywikis[0]['title']
			@fileid = @mywikis[0]['id']
			@userid = @mywikis[0]['userid']
			@user_record = MywikiUser.find(@userid)
			@pageuser = @user_record['user']
		end	
	end
  end

  # Display the help page. All logged in users have access.
  def help
	gen_content
	get_user
  end

  # If user has delete permission delete the specified page specified by :id, 
  # otherwise redirect user to mywiki index page.
  def destroy
	@page = "destroy"; p 'Page: '+@page
	get_user
	@priv = @user['d_priv']
	if @priv == false 
	  flash[:error] = 'You do not have permission to delete pages'
	  #	  redirect_to :back
	  redirect_to :action => :index		
	else 
		@mywikis = Mywiki.find(params[:id]);
		p @mywikis
		p ' destroying...'
		if @mywikis.destroy
			flash[:notice] = 'Page was successfully deleted.'
	        redirect_to :action => :index
		else
			flash[:error] = 'Page could not be deleted.'
		end
	end
  end

  # Display the search page 
  def search
	gen_content
	get_user
	@mywikis = Mywiki.find_by_contents(params[:searchkey])	
	#@mywikis = Mywiki.find(:all, :conditions => "tags like '%"+params[:searchkey]+"%' or description like '%"+params[:searchkey]+"%' or body like '%"+params[:searchkey]+"%' or title like '%"+params[:searchkey]+"%'")	
  end
  
  # Access to /mywiki/<anything> from url will be redirected to viewing wiki
  # page with title <anything>
  def method_missing( *args )
    p 'rediredcting...'
    p args[0]
    redirect_to( :action => 'view', :f => args[0] )
  end
  
  def load_test_data
	1.upto(20) { |n| 
		@mywiki = Mywiki.find(:all, :conditions => "title='TestTitle"+n.to_s+"'")
		if @mywiki.length == 0
			@mywiki = Mywiki.new(:title => 'TestTitle'+n.to_s, :tags => 'tags'+n.to_s, :description => 'test desc'+n.to_s, :body => 'test body '+n.to_s, :userid => 1);			
			@mywiki.save
		end
	}
	redirect_to :action => :help
  end
  
  
  private
  
  def gen_content
	@recent = Mywiki.find(:all, :select => "distinct *", :limit => 10, :order => "updated_at desc" )	
  end
  
  # Check if user is logged in, otherwise redirect to login page
  def get_user
	p 'In get user...'
	@id=session[:user_id]
	#@id=session[:user]
	if @id.nil?
		flash[:error] = 'You do not have permission';		
		redirect_to :controller => 'home', :action => :index
	else
		@user = MywikiUser.find(@id)
		p @user
		if @user.a_priv == true
			@manage = true
		end
	end
  end
end
